<script setup lang="ts">
import * as echarts from 'echarts'
import { ECharts, EChartsOption } from 'echarts'
import { EChartsUtil, getLinesStyle, outlineLineFormatter } from '@utils/echarts'
import { EmptyEnum, EmptyState } from '@yk/components/empty-box/type'
import YkEmptyBox from '@yk/components/empty-box/YkEmptyBox.vue'
import { AlarmHistoryDTO } from '@/api/entity/alarm'
import { ObjectUtil } from '@utils/object-util'
import { AlarmUtil } from '@utils'
import { getVariableHistoryByDateAPI } from '@/api/history'
import { DateFormat, moment } from '@utils/moment'

const props = withDefaults(defineProps<{
  alarm?: string | AlarmHistoryDTO
}>(), {
})

onMounted(() => {
  initDataChart()
  init()
})

const alarmInfo = shallowRef<AlarmHistoryDTO>()

watch(() => props.alarm, init)

function init () {
  if (typeof props.alarm === 'string') {
    getAlarmInfo()
  } else {
    alarmInfo.value = props.alarm
    getChartData()
  }
}

// 获取报警信息
function getAlarmInfo () {
  getChartData()
}

// 获取曲线数据
function getChartData () {
  dataChartState.value = EmptyEnum.LOADING
  getVariableHistoryByDateAPI({
    tableName: alarmInfo.value.deviceId,
    variableIds: [alarmInfo.value.variableId],
    startTime: alarmInfo.value.alarmAt,
    endTime: alarmInfo.value.recoverAt || moment().format(DateFormat.DateTime)
  }).finally(() => {
    dataChartState.value = EmptyEnum.SUCCESS
  }).then((res) => {
    res.result().then((rdata) => {
      // rdata.data = [
      //   {
      //     variableId: '1727942476968366081',
      //     variableVOList: [
      //       { ts: '2020-12-12 12:12:12', value: '220', unit: 'C' },
      //       { ts: '2020-12-13 12:12:12', value: '221' },
      //       { ts: '2020-12-14 12:12:12', value: '219' },
      //       { ts: '2020-12-15 12:12:12', value: '222' }
      //     ]
      //   }
      // ]
      const data = rdata.data[0]?.variableVOList || []
      if (data.length) {
        dataChart.value.setOption({
          yAxis: [{ name: data[0].unit }],
          series: [{
            data: data.map(item => [item.ts, item.value])
          }]
        })
      } else {
        dataChartState.value = EmptyEnum.EMPTY
      }
    })
  })
}

// function getData () {
//   getDataChartData()
// }

// region TODO 报警曲线
const dataChartRef = shallowRef<HTMLDivElement>()
const dataChart = shallowRef<ECharts>()
const dataChartState = shallowRef<EmptyState>(EmptyEnum.NONE)
function initDataChart () {
  dataChart.value = echarts.init(dataChartRef.value)
  dataChart.value.setOption(getLinesStyle({
    colors: ['#1570BB', '#FC5555'],
    names: ['历史数据', '设备离线'],
    area: true
  }).setLegend({ show: false })
    .addZoom({ start: 0, end: 100 })
    .setTooltip({ formatter: outlineLineFormatter }).getResult())
  EChartsUtil.addResizeListener(dataChart.value)
}
// function getDataChartData () {
//   // 模拟数据
//   const data = [
//     ['2020-12-12 2:12:17', 2],
//     ['2020-12-12 3:12:17', 10],
//     ['2020-12-12 4:12:17', 17],
//     ['2020-12-12 5:12:17', 12],
//     ['2020-12-12 06:00:00', 12],
//     ['2020-12-12 12:12:12', 12],
//     ['2020-12-12 12:12:13', 14],
//     ['2020-12-12 14:12:13', 16],
//     ['2020-12-12 14:12:16', 12],
//     ['2020-12-12 17:12:13', 10],
//     ['2020-12-12 17:15:13', 12]
//   ]
//   // 模拟上下线数据
//   const offLineData = [
//     { time: '2020-12-12 2:12:11', type: 1 },
//     { time: '2020-12-12 06:00:00', type: 0 },
//     { time: '2020-12-12 08:00:00', type: 1 },
//     { time: '2020-12-12 15:12:11', type: 0 },
//     { time: '2020-12-12 17:12:11', type: 1 }
//   ]
//   const data2 = []
//   let j = 0
//   for (let i = 0, len = offLineData.length; i < len; i++) {
//     const item = offLineData[i]
//     data2.push([item.time, 0])
//     if (item.type !== 0) {
//       data2.push([item.time, null])
//       continue
//     }
//     const time = new Date(item.time).getTime()
//     for (; j < data.length; j++) {
//       const time2 = new Date(data[j][0]).getTime()
//       if (time2 > time) {
//         if (j !== 0) {
//           data.splice(j, 0, [time, null])
//           j++
//         }
//         break
//       }
//     }
//   }
//   dataChart.value.setOption({
//     yAxis: { name: '℃' },
//     series: [
//       { data },
//       { data: data2 }
//     ]
//   } as EChartsOption)
//   dataChartState.value = EmptyEnum.SUCCESS
//   // dataChartState.value = { type: EmptyEnum.EMPTY, description: '暂无曲线数据' }
// }
onBeforeUnmount(() => {
  EChartsUtil.removeResizeListener(dataChart.value)
})
// endregion

//  region TODO 报警曲线
// const dataChartRef = shallowRef<HTMLDivElement>()
// const dataChart = shallowRef<ECharts>()
// const dataChartState = shallowRef<EmptyState>(EmptyEnum.NONE)
// function initDataChart () {
//   dataChart.value = echarts.init(dataChartRef.value)
//   dataChart.value.setOption(getLinesStyle({
//     colors: ['#1570BB', '#FC5555'],
//     names: ['历史数据', '设备离线'],
//     area: true
//   }).setLegend({ show: false })
//     .addZoom({ start: 0, end: 100 })
//     .setTooltip({ formatter: outlineLineFormatter }).getResult())
//   EChartsUtil.addResizeListener(dataChart.value)
// }
// function getDataChartData () {
//   // 模拟数据
//   const data = [
//     ['2020-12-12 2:12:17', 2],
//     ['2020-12-12 3:12:17', 10],
//     ['2020-12-12 4:12:17', 17],
//     ['2020-12-12 5:12:17', 12],
//     ['2020-12-12 06:00:00', 12],
//     ['2020-12-12 12:12:12', 12],
//     ['2020-12-12 12:12:13', 14],
//     ['2020-12-12 14:12:13', 16],
//     ['2020-12-12 14:12:16', 12],
//     ['2020-12-12 17:12:13', 10],
//     ['2020-12-12 17:15:13', 12]
//   ]
//   // 模拟上下线数据
//   const offLineData = [
//     { time: '2020-12-12 2:12:11', type: 1 },
//     { time: '2020-12-12 06:00:00', type: 0 },
//     { time: '2020-12-12 08:00:00', type: 1 },
//     { time: '2020-12-12 15:12:11', type: 0 },
//     { time: '2020-12-12 17:12:11', type: 1 }
//   ]
//   const data2 = []
//   let j = 0
//   for (let i = 0, len = offLineData.length; i < len; i++) {
//     const item = offLineData[i]
//     data2.push([item.time, 0])
//     if (item.type !== 0) {
//       data2.push([item.time, null])
//       continue
//     }
//     const time = new Date(item.time).getTime()
//     for (; j < data.length; j++) {
//       const time2 = new Date(data[j][0]).getTime()
//       if (time2 > time) {
//         if (j !== 0) {
//           data.splice(j, 0, [time, null])
//           j++
//         }
//         break
//       }
//     }
//   }
//   dataChart.value.setOption({
//     yAxis: { name: '℃' },
//     series: [
//       { data },
//       { data: data2 }
//     ]
//   } as EChartsOption)
//   dataChartState.value = EmptyEnum.SUCCESS
//   // dataChartState.value = { type: EmptyEnum.EMPTY, description: '暂无曲线数据' }
// }
// onBeforeUnmount(() => {
//   EChartsUtil.removeResizeListener(dataChart.value)
// })
// endregion
</script>

<template>
  <div>
    <template v-if="alarmInfo">
      <!--报警信息-->
      <div class="d-flex">
        <!--报警状态-->
        <div class="position-relative d-flex-center" style="width: 80px;aspect-ratio: 1;" :class="[alarmInfo.alarmState ? 'color-danger' : 'color-success' ]">
          <ic-bor-annulus style="font-size: 80px;" class="position-absolute" />
          <span>{{ alarmInfo.alarmState ? '报警中' : '已恢复' }}</span>
        </div>
        <!--报警信息-->
        <div class="d-grid flex-1 mx-40 py-12 fs-14 alarm-info" style="">
          <div>{{ alarmInfo.deviceName }}</div>
          <div class="d-flex align-items-center">
            <ic-system-circle class="color-danger" />
            <span class="label ml-8">报警时间：</span>
            <span class="value">{{ alarmInfo.alarmAt }}</span>
          </div>
          <div>
            <span class="label">变量值：</span>
            <span class="value">{{ alarmInfo.alarmValue }}</span>
          </div>
          <div>
            <span class="label">报警变量：</span>
            <span class="value">{{ alarmInfo.variableName }}</span>
          </div>
          <div class="d-flex align-items-center">
            <ic-system-circle class="color-success" />
            <span class="label ml-8">恢复时间：</span>
            <span class="value">{{ alarmInfo.recoverAt || '/' }}</span>
          </div>
          <div>
            <span class="label">变量值：</span>
            <span class="value">{{ ObjectUtil.isEmptyToVal(alarmInfo.recoverValue, '/') }}</span>
          </div>
        </div>
      </div>
      <!--触发条件-->
      <div class="mt-24 fs-14 p-12 bg-color-primary-light-9">
        <span class="color-secondary">触发条件：</span>
        <span>{{ AlarmUtil.formatCondition(alarmInfo.rule) }}</span>
      </div>
    </template>
    <!--报警曲线-->
    <div class="mt-20">
      <div class="text-color-primary fs-16">报警曲线</div>
      <yk-empty-box :state="dataChartState">
        <div ref="dataChartRef" class="mt-12 bor-divider" style="height: 378px;" />
      </yk-empty-box>
    </div>
  </div>
</template>

<style scoped lang="scss">
.alarm-info {
  grid-template-columns: 193px 291px 1fr;
  grid-gap: 16px;
  .label {
    color: var(--yk-color-secondary);
  }
  .value {
    color: var(--el-text-color-primary)
  }
}
</style>
